package com.sh.caryr.erp.controller.stock;


import com.baomidou.mybatisplus.mapper.Wrapper;
import com.sh.caryr.erp.entity.PageResultMessage;
import com.sh.caryr.erp.entity.ResultMessage;
import com.sh.caryr.erp.entity.stock.Storage;
import com.sh.caryr.erp.exception.ResultCode;
import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.exception.RestServiceException;
import com.sh.caryr.erp.service.IStorageService;
import com.sh.caryr.erp.util.ERPConstants;
import com.sh.caryr.erp.util.MyBatisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 仓库表 前端控制器
 * </p>
 *
 * @author milkeeper
 * @since 2017-11-22
 */
@RestController
@RequestMapping("/api/storage")
@SessionAttributes("user")
public class StorageController {

    @Autowired
    private IStorageService storageService;

    @RequestMapping(method = RequestMethod.GET)
    public ResultMessage<List<Storage>> findStorages(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(required = false) Integer size,
            @RequestParam(required = false) String queryField,
            @RequestParam(required = false) String queryValue,
            @RequestParam(required = false) Boolean isAccurate,
            @RequestParam(defaultValue = "id") String orderBy,
            @ModelAttribute("user") User operator) {
        Wrapper wrapper = MyBatisUtil.getActiveQueryWrapper(queryField, queryValue);
        MyBatisUtil.addAuthFilter(wrapper, operator, ERPConstants.AUTH_TARGET_STORAGE, false, false);
        List<Storage> storageList = storageService.findEnittyDynamic(current, size, wrapper, orderBy);
        return new PageResultMessage<>(storageList, storageService.selectCount(wrapper));
        //return storageService.selectList(null);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Storage findStorageById(@PathVariable long id) {
        Storage storage = storageService.selectById(id);
        if (storage == null) {
            throw new RestServiceException(HttpStatus.NOT_FOUND, ResultCode.ENTITY_NOT_FOUND);
        }
        return storage;
    }

    @RequestMapping(method = RequestMethod.POST)
    public Object insertStorage(@RequestBody Storage storage) {
        return storageService.insert(storage) ? ("添加成功") : ("添加失败");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Object updateStorageById(@PathVariable long id, @RequestBody Storage storage) {
        storage.setId(id);
        return storageService.updateById(storage) ? ("修改成功") : ("修改失败");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Object deleteStorageById(@PathVariable long id) {
        return storageService.deleteById(id) ? ("删除成功") : ("删除失败");
    }
}
